package cn.com.shopec.erp.common.utils;

import java.io.PrintWriter;
import java.lang.reflect.Type;

import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class JsonHelper {
	private static Gson gson = new GsonBuilder()
			.setDateFormat("yyyy年MM月dd日 HH:mm:ss").disableHtmlEscaping()
			.create();

	public static <T> T fromJson(String json, Class<T> clazz) {
		return (T) gson.fromJson(json, clazz);
	}

	public static <T> T fromJson(String json, Type typeOfT) {
		return (T) gson.fromJson(json, typeOfT);
	}

	public static String toJson(Object obj) {
		return gson.toJson(obj);
	}

	public static void sendToWeb(HttpServletResponse response, Object result)
			throws Exception {
		sendToWeb(response, "application/json; charset=UTF-8", 200,
				gson.toJson(result));
	}

	public static void sendToWeb(HttpServletResponse response,
			String exception, Object result) throws Exception {
		sendToWeb(response, "application/json; charset=UTF-8", 200,
				gson.toJson(exception), gson.toJson(result));
	}

	public static void fromUpload(HttpServletResponse response, Object result)
			throws Exception {
		sendToWeb(response, "text/html; charset=UTF-8", 200,
				gson.toJson(result));
	}

	public static void throwException(HttpServletResponse response,
			Object result) throws Exception {
		sendToWeb(response, "application/json; charset=UTF-8", 500, result);
	}

	private static void sendToWeb(HttpServletResponse response,
			String contentType, int status, Object result) throws Exception {
		// System.out.println("result: " + result);
		response.setContentType(contentType);
		response.setHeader("Cache-Control", "no-cache");
		response.setStatus(status);

		PrintWriter out = response.getWriter();
		out.print(result);

		out.flush();
		out.close();
	}

	private static void sendToWeb(HttpServletResponse response,
			String contentType, int status, Object exception, Object result)
			throws Exception {
		// System.out.println("result: " + result);
		response.setContentType(contentType);
		response.setHeader("Cache-Control", "no-cache");
		response.setStatus(status);
		StringBuilder sb = new StringBuilder("{");
		sb.append("\"exception\":" + exception + ",");
		sb.append("\"result\":" + result + "}");
		PrintWriter out = response.getWriter();
		out.print(sb.toString());
		out.flush();
		out.close();
	}
}
